<template>
  <div class="goodsDetail-container  ">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item>首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品详情</el-breadcrumb-item>
    </el-breadcrumb>
    <div class="detail-title">
      <el-alert v-if="!isEdit" title='添加商品信息' type="success" center>
      </el-alert>
      <el-alert v-else title='修改商品信息' type="warning" center>
      </el-alert>
    </div>
    <!-- 步骤条 -->
    <!-- active接收的是一个数字类型 -->
    <el-steps :active="activeIndex-0" align-center>
      <el-step title="商品信息" icon="el-icon-edit"></el-step>
      <el-step title="商品图片" icon="el-icon-picture-outline"></el-step>
      <el-step title="商品内容" icon="el-icon-document"></el-step>
    </el-steps>
    <!-- tab -->
    <el-tabs tab-position="left" v-model='activeIndex' class="tab-box" :before-leave='changeTabBefore'>
      <el-tab-pane label="商品信息" name="0">
        <!-- 商品信息tab -->
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm" label-position="top" :headers='headerObj'>
          <el-form-item label="商品名称" prop="name">
            <el-input v-model="ruleForm.name"></el-input>
          </el-form-item>
          <el-form-item label="商品价格（小数支持小数点后两位）" prop="price">
            <el-input v-model="ruleForm.price" type="number"></el-input>
          </el-form-item>
          <el-form-item label="已售（数字）" prop="sellNum">
            <el-input v-model="ruleForm.sellNum" type="number"></el-input>
          </el-form-item>
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="商品图片" name="1">
        <!-- 上传商品图片tab -->
        <el-upload ref="files" :on-change="addFile" class="upload-demo" :action='uploadUrl' :on-preview="handlePreview" :on-remove="handleRemove" :on-success='handleUpload' list-type="picture" :limit="1">
          <el-button size="small" type="success">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
        </el-upload>
      </el-tab-pane>
      <el-tab-pane label="商品内容" name="2">
        <!-- 商品内容 -->
        <!-- 使用el上传组件配合编辑器 -->
        <el-upload class="avatar-uploader" :action='uploadUrl' name="img" :show-file-list="false" :on-success="uploadSuccess">
        </el-upload>
        <!-- 编辑器 -->
        <quill-editor class='editor' ref="myQuillEditor" v-model="content" :options="editorOption" @blur="onEditorBlur($event)" @focus="onEditorFocus($event)" @ready="onEditorReady($event)" />
        <el-button type="success" class="submitBtn" @click="submit">发布商品</el-button>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
const toolbarOptions = [
  ['bold', 'italic', 'underline', 'strike'], // 加粗，斜体，下划线，删除线
  ['blockquote', 'code-block'],
  [{ header: 1 }, { header: 2 }], // 几级标题
  [{ list: 'ordered' }, { list: 'bullet' }], // 有序列表，无序列表
  [{ script: 'sub' }, { script: 'super' }], // 下角标，上角标
  [{ indent: '-1' }, { indent: '+1' }], // 缩进
  [{ direction: 'rtl' }], // 文字输入方向
  [{ size: ['small', false, 'large', 'huge'] }], // 字体大小
  [{ header: [1, 2, 3, 4, 5, 6, false] }], // 标题
  [{ color: [] }, { background: [] }], // 颜色选择
  [{ font: ['SimSun', 'SimHei', 'Microsoft-YaHei', 'KaiTi', 'FangSong', 'Arial'] }], // 字体
  [{ align: [] }], // 居中
  ['clean'], // 清除样式,
  ['link', 'image'] // 上传图片、上传视频
]

export default {
  name: 'GdCom',
  data() {
    return {
      uploadUrl: process.env.VUE_APP_BASEURL + '/api/upload',
      isEdit: false,
      // 因为tab双向绑定必须是字符串
      activeIndex: '0',
      ruleForm: {
        name: '',
        price: 0,
        sellNum: 0
      },
      rules: {
        name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        price: [{ required: true, message: '请输入商品价格', trigger: 'blur' }],
        sellNum: [{ required: true, message: '请输入已售数量', trigger: 'blur' }]
      },
      content: '',
      // 富文本编辑器配置

      editorOption: {
        placeholder: '请在这里输入',
        theme: 'snow',
        modules: {
          history: {
            delay: 1000,
            maxStack: 50,
            userOnly: false
          },
          toolbar: {
            container: toolbarOptions,
            handlers: {
              image: function (value) {
                if (value) {
                  // 调用element的图片上传组件
                  document.querySelector('.avatar-uploader input').click()
                } else {
                  this.quill.format('image', false)
                }
              }
            }
          }
        }
      },
      // 上传商品图片相关
      dialogImageUrl: '',
      dialogVisible: false,
      disabled: false,
      pit: {},
      headerObj: { 'Content-Type': 'multipart/form-data' },
      imgUrl: ''
    }
  },
  methods: {
    // 获取商品信息
    async getGoodsInfo() {
      const editId = this.$route.params.id
      const { data: rel } = await this.$http.get(`goods/${editId}`)
      this.ruleForm.name = rel.data.goods_name
      this.ruleForm.price = rel.data.goods_price
      this.ruleForm.sellNum = rel.data.goods_sellNum
      this.imgUrl = rel.data.goods_img
      this.content = rel.data.goods_content
    },
    // 发布商品
    async submit() {
      if (this.isEdit) {
        const newInfo = {
          newName: this.ruleForm.name,
          newPrice: this.ruleForm.price,
          newSellNum: this.ruleForm.sellNum,
          newGoodsImg: this.imgUrl,
          newContent: this.content
        }
        const { data: rel } = await this.$http.put(`goods/${this.$route.params.id}`, newInfo)
        if (rel.code === 20000) {
          this.$message({
            message: '修改商品成功',
            type: 'success'
          })
        } else {
          this.$message.error('修改失败')
        }
      } else {
        if (this.pit instanceof FormData === false) {
          alert('请上传商品图片【必须】')
          return false
        }
        // console.log(this.imgUrl)
        const goodsInfo = {
          name: this.ruleForm.name,
          price: this.ruleForm.price,
          sellNum: this.ruleForm.sellNum,
          goodsImg: this.imgUrl,
          content: this.content
        }
        const { data: rel } = await this.$http.post('goods', goodsInfo)
        if (rel.code === 20000) {
          this.$message({
            message: '添加商品成功',
            type: 'success'
          })
        }
      }
      this.$router.replace('/home/goods')
    },
    // 切换tab之前触发
    changeTabBefore(activeName, oldActiveName) {
      console.log(activeName)
      console.log(oldActiveName)
      // 判断商品是否填写了名称
      if (this.ruleForm.name === '') {
        this.$message({
          message: '还没有填写商品名称',
          type: 'warning'
        })
        // 阻止切换tab
        return false
      }
    },
    // 上传图片相关
    handleRemove(file, fileList) {
      console.log(file, fileList)
    },
    handlePreview(file) {
      console.log(file)
    },
    // 上传图片的钩子
    addFile(file) {
      const pit = new FormData()
      pit.append('goodsImg', file.raw)
      this.pit = pit
    },
    // 上传图片成功的钩子
    handleUpload(response) {
      // console.log(response.url)
      this.imgUrl = response.url
    },
    // 富文本相关
    // 失去焦点事件
    onEditorBlur(quill) {
      // console.log('editor blur!', quill)
    },
    // 获得焦点事件
    onEditorFocus(quill) {
      // console.log('editor focus!', quill)
    },
    // 准备富文本编辑器
    onEditorReady(quill) {
      // console.log('editor ready!', quill)
    },
    uploadSuccess(res) {
      // 获取富文本组件实例
      const quill = this.$refs.myQuillEditor.quill
      // 如果上传成功
      if (res) {
        // 获取光标所在位置
        const length = quill.getSelection().index
        // 插入图片，res为服务器返回的图片链接地址
        const newUrl = process.env.VUE_APP_BASEURL + res.url
        quill.insertEmbed(length, 'image', newUrl)
        // 调整光标到最后
        quill.setSelection(length + 1)
      } else {
        // 提示信息，需引入Message
        this.$message.error('图片插入失败！')
      }
    }
  },
  created() {
    if (this.$route.params.id) {
      this.isEdit = true
      this.getGoodsInfo()
    }
    console.log(this.isEdit)
    console.log(process.env.VUE_APP_DEMO)
  }
}
</script>

<style scoped>
.detail-title {
  margin: 20px 0;
}
.tab-box {
  margin-top: 20px;
}
.submitBtn {
  margin-top: 20px;
}
</style>
